package biz

import "github.com/pkg/errors"

type TaskRepo interface {
	Create(task *Task) (*Task, error)
	Update(id uint, task *TaskUpdate) (*Task, error)
	List(cond *TaskCondition) ([]*Task, error)
	Find(cond *TaskCondition) (*Task, error)
	Exist(cond *TaskCondition) bool
}

type TaskBiz struct {
	repo TaskRepo
}

func NewTaskBiz(repo TaskRepo) *TaskBiz {
	return &TaskBiz{
		repo: repo,
	}
}

func (biz *TaskBiz) Create(task *Task) (*Task, error) {

	cond := &TaskCondition{
		TaskName: task.TaskName,
	}

	if biz.repo.Exist(cond) {
		return nil, errors.Errorf("task already exists of: %s", cond.TaskName)
	}

	return biz.repo.Create(task)
}

func (biz *TaskBiz) List(cond *TaskCondition) ([]*Task, error) {
	return biz.repo.List(cond)
}

func (biz *TaskBiz) Update(id uint, d *TaskUpdate) (*Task, error) {
	if !biz.repo.Exist(&TaskCondition{
		ID: id,
	}) {
		return nil, errors.Errorf("task already exists of ID: %d", id)
	}

	task, err := biz.repo.Update(id, d)
	if err != nil {
		return nil, err
	}

	return task, nil
}
